<?php
import("data.logic.catalogue.Catalogue");
import("data.logic.catalogue.Node");

class CatalogueFactory {
	
	function CatalogueFactory() {
	}
	
	/**
	* @return Object
	* @param String $cname
	* @desc Try to create new Catalogue in database 
	*/
	function createCatalogue($cname) {
		if (Catalogue::findByName($cname)!=null) {
			throw new Exception("Catalogue with '".$cname."' is exists");
		}

		try {
			$cat = new Catalogue();
			$cat->setName($cname);
			$cat->store();
			
			$rootNode = new Node();
			$rootNode->setName("root");
			$rootNode->setCatalogue($cat);
			$rootNode->store();
		} catch (Exception $e) {
			throw new Exception("Can't create new Catalogue");
		}
		return $cat;
	}
	
	/**
	* @return Object
	* @param String $cname
	* @desc Retrive founded Catalogue
	*/
	function findCatalogue($cname) {
		return Catalogue::findByName($cname);
	}
	
	function createRemoteCatalogue($url, $cat_id) {
		try {
			import("data.logic.catalogue.RemoteCatalogue");
			import("data.logic.catalogue.Node");
			import("data.logic.lingvo.Lingvo");
			
			return new RemoteCatalogue($url, $cat_id);
		} catch (Exception $e) {
			throw new Exception("Can't get remote catalogue.");
		}
	}
	
	function createNode($cat_id, $parent_node_id, $node_name) {
		$catalogue = Catalogue::findById($cat_id);
		if ($catalogue) {
			$parent = $catalogue->findNodeById($parent_node_id);
			if ($parent) {
				try {
					$newnode = new Node();
					$newnode->setName($node_name);
					$parent->addNode($newnode);
				} catch (Exception $e) {
					echo $e;
				}
			}
		}
	}
}
?>